﻿namespace EyeOpen.Data.Nhibernate
{
    using EyeOpen.Data;
    using EyeOpen.Domain;
    using NHibernate;

    public abstract class NhibernateDataContext : BaseDataContext
    {
        private readonly ISession session;

        private ITransaction transaction;

        protected NhibernateDataContext(ISession session)
        {
            this.session = session;
        }

        protected ISession Session
        {
            get
            {
                return session;
            }
        }

        public override void BeginTransaction()
        {
            if (transaction == null)
            {
                transaction = Session.BeginTransaction();
            }
        }

        public override void SaveChanges()
        {
            if (transaction == null)
            {
                Session.Flush();
            }
            else
            {
                if (transaction.IsActive)
                {
                    try
                    {
                        transaction.Commit();
                    }
                    catch
                    {
                        transaction.Rollback();
                    }
                    finally
                    {
                        transaction.Dispose();
                    }
                }
            }
        }

        public override void Dispose()
        {
            if (transaction != null)
            {
                transaction.Dispose();
            }

            if (Session != null)
            {
                Session.Dispose();
            }
        }

        public override void Commit()
        {
            transaction.Commit();
            transaction = null;
        }

        public override void Rollback()
        {
            transaction.Rollback();
            transaction = null;
        }

        protected override void Save(UniqueEntity entity)
        {
            CheckEntity(entity);
            Session.Save(entity);
        }
    }
}